import './TeacherExamPage.scss'
import { localGetTestCheckAPI } from '@/apis/student';
import { useNavigate } from 'react-router-dom';
import { DoubleLeftOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, ConfigProvider, Input, message, Radio, InputNumber, Empty } from 'antd';
import Form from 'antd/es/form/Form';
import { useEffect, useState } from 'react';
import CheckItem from './components/CheckItem/CheckItem';
import { useSelector, useDispatch } from 'react-redux';
import { fetchGetTests } from '@/store/modules/teacher';

import { addTestsAPI, changeTestInfoAPI, deleteTestsAPI } from '@/apis/teacher';



export default function TeacherExamPage() {
    const dispatch = useDispatch();
    const { user_status } = useSelector(state => state.user);
    const { tests } = useSelector(state => state.teacher);
    const [checkList, setCheckList] = useState([]);
    const navigate = useNavigate();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [newTestName, setNewTestName] = useState('');
    const [testType, setTestType] = useState('选择');
    const [newTestScore, setNewTestScore] = useState(1);
    const [newBlankNum, setNewBlankNum] = useState(1);
    const [blankList, setBlankList] = useState([]);
    const [newTestChoices, setNewTestChoices] = useState(['', '', '', '']);
    const [choiceAnswer, setChoiceAnswer] = useState('A');
    const [isChangeTestModelOpen, setIsChangeTestModelOpen] = useState(false);
    const [changeTestId, setChangeTestId] = useState('');

    const handleBackClick = function () {
        navigate('/teachercourse/test');
    }

    const showModal = () => {
        setIsModalOpen(true);
    };

    const showChangeTestModel = (exercise_id) => {
        setChangeTestId(exercise_id);
        setIsChangeTestModelOpen(true);
    }

    const handleAddTest = async () => {
        setLoading(true);
        if (testType === '选择') {
            const res = await addTestsAPI([{
                class_id: user_status.class_id,
                exe_name: newTestName,
                exe_type: testType,
                points: newTestScore,
                exe_choices: {
                    A: newTestChoices[0],
                    B: newTestChoices[1],
                    C: newTestChoices[2],
                    D: newTestChoices[3],
                },
                exe_answer: choiceAnswer,
                exe_parts: user_status.partid
            }], user_status.token)
            console.log(res);
        }


        if (testType === '填空') {
            const res = await addTestsAPI([{
                class_id: user_status.class_id,
                exe_name: newTestName,
                exe_type: testType,
                points: newTestScore,
                exe_blank_num: newBlankNum,
                exe_answer: blankList.join(' '),
                exe_parts: user_status.partid
            }], user_status.token)
            console.log(res);
        }
        message.success('添加成功');
        setIsModalOpen(false);
        window.location.reload();
        setLoading(false);
    };

    const handleCancelAddTest = async () => {
        setIsModalOpen(false);
    };

    const handleSelectType = (e) => {
        setTestType(e.target.value);
    }

    const handleNewTestBlankChange = (content, key) => {
        setBlankList(blankList.map((ele, index) => (index === key ? content : ele)));
        // console.log(blankList);
    }

    const handleNewChoices = (content, key) => {
        setNewTestChoices(newTestChoices.map((ele, index) => (index === key ? content : ele)));
        // console.log(newTestChoices);
    }

    const handleEditTest = async () => {
        setLoading(true);
        if (testType === '选择') {
            const res = await changeTestInfoAPI([{
                class_id: user_status.class_id,
                exercise_id: changeTestId,
                exe_name: newTestName,
                exe_type: testType,
                points: newTestScore,
                exe_choices: {
                    A: newTestChoices[0],
                    B: newTestChoices[1],
                    C: newTestChoices[2],
                    D: newTestChoices[3],
                },
                exe_answer: choiceAnswer,
                exe_parts: user_status.partid
            }], user_status.token)
            console.log(res);
        }


        if (testType === '填空') {
            const res = await changeTestInfoAPI([{
                class_id: user_status.class_id,
                exercise_id: changeTestId,
                exe_name: newTestName,
                exe_type: testType,
                points: newTestScore,
                exe_blank_num: newBlankNum,
                exe_answer: blankList.join(' '),
                exe_parts: user_status.partid
            }], user_status.token)
            console.log(res);
        }
        message.success('添加成功');
        setIsModalOpen(false);
        window.location.reload();
        setLoading(false);


        setIsChangeTestModelOpen(false);
    }

    const handleCancelEdit = () => {
        setIsChangeTestModelOpen(false);
    }

    const handleDeleteTest = () => {
        const res = deleteTestsAPI([{
            class_id: user_status.class_id,
            exe_parts: user_status.partid,
            exercise_id: changeTestId
        }], user_status.token);
        console.log(res);
        window.location.reload();
        setIsChangeTestModelOpen(false);
    }

    useEffect(() => {
        async function getCheckList() {
            dispatch(fetchGetTests({
                class_id: user_status.class_id,
                partid: user_status.partid
            }, user_status.token));

            const res = await localGetTestCheckAPI();
            for (let i = 0; i < res.data.length; i++) {
                res.data[i].key = i;
            }


            setCheckList(res.data);
        }

        getCheckList();


    }, []);

    useEffect(() => {
        setBlankList(Array(newBlankNum).fill(''));
    }, [newBlankNum])

    return (
        <div className='TeacherExamPage'>
            <header>
                <button onClick={handleBackClick}> <DoubleLeftOutlined /> 返回</button>
                <h1>第{user_status.partid}章测验习题</h1>
            </header>
            <ConfigProvider
                theme={{
                    token: {
                        // Seed Token，影响范围大
                        colorPrimary: '#2486b9',
                        borderRadius: 5,

                        // 派生变量，影响范围小
                        // colorBgContainer: '#f6ffed',
                    },
                }}
            >
                <Form
                    className='check-form'
                    layout='vertical'
                    disabled={true}
                >
                    {
                        tests.length === 0 ||
                        (
                            tests[0].success ?
                                tests.map((ele, index) => <CheckItem key={index} opEditModel={showChangeTestModel} info={ele} />)
                                : <Empty
                                    className='empty'
                                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                                    description={
                                        <span>
                                            你还没有添加习题，点击右下角的图标添加
                                        </span>
                                    }
                                />
                        )
                    }
                </Form>
                <Button
                    type="primary"
                    onClick={showModal}
                    className='add-video'
                >
                    <PlusOutlined />
                </Button>
                <Modal
                    title={<h3>新增试题</h3>}
                    open={isModalOpen}
                    onCancel={handleCancelAddTest}
                    footer={[
                        <Button key="back" onClick={handleCancelAddTest}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleAddTest}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newtestname'>请输入新增试题的题干</label>
                    <Input id='newtestname' onInput={function (e) { setNewTestName(e.target.value) }} value={newTestName} />
                    <div>请输入该题的分值</div>
                    <InputNumber min={1} max={10} onChange={(value) => { setNewTestScore(value) }} value={newTestScore} />
                    <div>请选择题型</div>
                    <Radio.Group
                        onChange={handleSelectType}
                        value={testType}
                        defaultValue={'选择'}
                    >
                        <Radio value={'选择'}>选择</Radio>
                        <Radio value={'填空'}>填空</Radio>
                    </Radio.Group>
                    {testType === '选择' ? (
                        <>
                            <div>请输入选项内容</div>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 0)} placeholder='A'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 1)} placeholder='B'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 2)} placeholder='C'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 3)} placeholder='D'></Input>
                            <div>请选择答案</div>
                            <Radio.Group
                                defaultValue={'A'}
                                onChange={(e) => { setChoiceAnswer(e.target.value) }}
                            >
                                <Radio value={'A'}>A</Radio>
                                <Radio value={'B'}>B</Radio>
                                <Radio value={'C'}>C</Radio>
                                <Radio value={'D'}>D</Radio>
                            </Radio.Group>
                        </>
                    ) : (
                        <>
                            <div>请输入填空数量</div>
                            <InputNumber min={1} max={3} value={newBlankNum} onChange={(value) => { setNewBlankNum(value) }} />
                            <div>请输入每一空的答案</div>
                            {blankList.map((ele, index) => <Input key={index} value={ele} onChange={(e) => handleNewTestBlankChange(e.target.value, index)} />)}
                        </>
                    )}
                </Modal>
                <Modal
                    title={<h3>修改试题信息</h3>}
                    open={isChangeTestModelOpen}
                    onCancel={handleCancelEdit}
                    footer={[
                        <Button danger key="delete" onClick={handleDeleteTest}>删除该题</Button>,
                        <Button key="back" onClick={handleCancelEdit}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleEditTest}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newtestname'>请输入新试题的题干</label>
                    <Input id='newtestname' onInput={function (e) { setNewTestName(e.target.value) }} value={newTestName} />
                    <div>请输入该题的分值</div>
                    <InputNumber min={1} max={10} onChange={(value) => { setNewTestScore(value) }} value={newTestScore} />
                    <div>请选择题型</div>
                    <Radio.Group
                        onChange={handleSelectType}
                        value={testType}
                        defaultValue={'选择'}
                    >
                        <Radio value={'选择'}>选择</Radio>
                        <Radio value={'填空'}>填空</Radio>
                    </Radio.Group>
                    {testType === '选择' ? (
                        <>
                            <div>请输入选项内容</div>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 0)} placeholder='A'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 1)} placeholder='B'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 2)} placeholder='C'></Input>
                            <Input onInput={(e) => handleNewChoices(e.target.value, 3)} placeholder='D'></Input>
                            <div>请选择答案</div>
                            <Radio.Group
                                defaultValue={'A'}
                                onChange={(e) => { setChoiceAnswer(e.target.value) }}
                            >
                                <Radio value={'A'}>A</Radio>
                                <Radio value={'B'}>B</Radio>
                                <Radio value={'C'}>C</Radio>
                                <Radio value={'D'}>D</Radio>
                            </Radio.Group>
                        </>
                    ) : (
                        <>
                            <div>请输入填空数量</div>
                            <InputNumber min={1} max={3} value={newBlankNum} onChange={(value) => { setNewBlankNum(value) }} />
                            <div>请输入每一空的答案</div>
                            {blankList.map((ele, index) => <Input key={index} value={ele} onChange={(e) => handleNewTestBlankChange(e.target.value, index)} />)}
                        </>
                    )}
                </Modal>
            </ConfigProvider>
        </div>
    )
}